<template>
  <div>
    <Table :list="list">
      <template v-slot:btn="obj">
        <button @click="see(obj.item)">查看详情</button>
        <button @click="del(obj.item.id)">删除</button>
        <button @click="edit(obj.item)">编辑</button>
      </template>
    </Table>
    <InfoPage
      :bookInfo="bookInfo"
      v-if="flag"
      :type="type"
      @cancel="cancel"
      @confirm="confirm"
    ></InfoPage>
    <button @click="add">添加</button>
  </div>
</template>
<script>
import axios from "axios";
import Table from "./06zuoye/book/Table.vue";
import InfoPage from "./06zuoye/book/InfoPage.vue";
export default {
  components: {
    Table,
    InfoPage,
  },
  data() {
    return {
      list: [],
      creator: "ccddd",
      bookInfo: {
        id: "",
        bookname: "",
        author: "",
        publisher: "",
      },
      flag: false,
      type: 1,
    };
  },
  created() {
    this.getData();
  },
  computed: {},
  methods: {
    async getData() {
      let res = await axios({
        url: "http://hmajax.itheima.net/api/books",
        params: {
          creator: this.creator,
        },
      });
      this.list = res.data.data;
    },
    del(id) {
      console.log(id);
      axios({
        url: `http://hmajax.itheima.net/api/books/${id}`,
        method: "DELETE",
      }).then((res) => {
        this.getData();
      });
    },
    edit(item) {
      this.flag = true;
      this.bookInfo = item;
      this.type = 1;
    },
    add() {
      this.flag = true;
      this.type = 1;
    },
    see(item) {
      this.type = 0;
      this.bookInfo = item;
      this.flag = true;
    },
    cancel() {
      this.flag = false;
      this.bookInfo = {
        id: "",
        bookname: "",
        author: "",
        publisher: "",
      };
    },
    confirm(val) {
      this.flag = false;
      if (val.id) {
        axios({
          url: `http://hmajax.itheima.net/api/books/${val.id}`,
          method: "PUT",
          data: {
            ...val,
          },
        }).then((res) => {
          this.getData();
        });
      } else {
        axios({
          url: "http://hmajax.itheima.net/api/books",
          method: "POST",
          data: {
            ...val,
            creator: this.creator,
          },
        }).then((res) => {
          this.getData();
        });
      }
      this.bookInfo = {
        id: "",
        bookname: "",
        author: "",
        publisher: "",
      };
    },
  },
};
</script>
<style lang='less'  scoped>
</style>
